<!--
 * @Author: wangming
 * @Date: 2021-04-08 15:17:17
 * @LastEditors: wangming
 * @LastEditTime: 2022-07-27 14:15:00
 * @Description: file content
-->
<template>
  <div>
    <el-form-item label="按钮类型">
      <el-select
        @change="chnageType"
        v-model="value.buttnType"
        placeholder="默认"
        style="width: 100%"
      >
        <el-option
          :value="i.key"
          :label="i.value"
          v-for="(i, index) in BUTTON_TYPES_ENUM"
          :key="index"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item
      label="选择打印设计"
      v-if="value.buttnType === 'print'"
      key="print"
    >
      <el-select
        v-model="value.printKey"
        placeholder="请选择"
        style="width: 100%"
      >
        <el-option
          :value="i.key"
          :label="i.name"
          v-for="(i, index) in printLists"
          :key="index"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item
      label="关联表单标识"
      v-if="
        value.buttnType.indexOf('form') > -1 ||
        value.buttnType === 'process_handle' ||
        value.buttnType === 'submit_close'
      "
    >
      <el-select
        v-model="value.formkey"
        placeholder="选择提交表单标识"
        style="width: 100%"
      >
        <el-option
          :value="i.key"
          :label="i.label"
          v-for="(i, index) in getFormListInTree"
          :key="index"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item
      label="流程处理类型"
      v-show="value.buttnType === 'process_handle'"
    >
      <el-select
        v-model="value.processType"
        placeholder="处理"
        style="width: 100%"
      >
        <el-option value="" label="处理"></el-option>
        <el-option value="transfer" label="转办"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item
      prop="processServeId"
      label="模型服务名称"
      v-show="value.buttnType === 'process_handle'"
    >
      <el-select
        clearable
        v-model="value.processServeId"
        placeholder="默认"
        style="width: 100%"
        @visible-change="changes"
      >
        <el-option
          :value="i.key"
          :label="i.name"
          v-for="(i, index) in processServelist"
          :key="index"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item
      label="关联流程"
      v-show="
        value.buttnType === 'process_start' ||
        value.buttnType === 'process_handle'
      "
    >
      <el-select
        v-model="value.processKey"
        placeholder="默认"
        style="width: 100%"
      >
        <el-option
          :value="i.key"
          :label="`${i.name}(${i.key})`"
          v-for="(i, index) in processlist"
          :key="index"
        ></el-option>
      </el-select>
    </el-form-item>
    <!--    链接按钮 关联页面-->
    <el-form-item
      label="关联页面标识"
      v-show="value.buttnType === 'link_redirect'"
    >
      <tree-select
        v-if="value.buttnType === 'link_redirect'"
        v-model="value.pageKey"
        style="width: 100%"
        @change="changePageItem"
        placeholder="请选择跳转的PC页面"
        filterable
        :fieldMap="{
          value: 'key',
          label: 'name',
          disabled: 'disabled',
        }"
        :filterNodeMethod="filterNodeMethod"
        :treeData="pageList"
      />
    </el-form-item>
    <!-- 导入导出模板 -->
    <el-form-item
      :label="value.buttnType === 'import' ? '导入模板' : '导出模板'"
      v-if="value.buttnType === 'export' || value.buttnType === 'import'"
    >
      <el-radio-group v-model="value.templateType" style="width: 100%">
        <el-radio label="SYSTEM">系统</el-radio>
        <el-radio label="CUSTOM">自定义</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 系统模板 -->
    <el-form-item
      v-if="
        (value.buttnType === 'export' || value.buttnType === 'import') &&
        value.templateType === 'SYSTEM'
      "
    >
      <el-select
        size="small"
        style="width: 100%"
        v-model="value.systemplateKey"
        placeholder="请选择模板"
        clearable
      >
        <el-option
          v-for="(item, index) in templateArr"
          :key="index"
          :value="item.key"
          :label="item.name"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <!-- 自定义模板 -->
    <el-form-item
      label="模板"
      class="tr"
      v-if="
        (value.buttnType === 'export' || value.buttnType === 'import') &&
        value.templateType !== 'SYSTEM'
      "
    >
      <div class="filebox ks-row-middle bgwh" v-if="!!value.tempalteURL">
        <div class="g3 ks-col ell f14">
          {{ value.tempalteURL }}
        </div>
        <el-button
          type="text"
          icon="el-icon-download"
          @click="download(value.tempalteURL)"
          >下载</el-button
        >
        <el-button
          type="text"
          icon="el-icon-delete"
          @click="value.tempalteURL = ''"
          >删除
        </el-button>
      </div>
      <common-upload
        v-else
        client
        @success="handleUploadSuccess"
        accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      >
        <el-button icon="el-icon-upload2" size="mini">上传</el-button>
      </common-upload>
    </el-form-item>
    <!-- 参数  -->
    <el-form-item
      label="导出参数"
      v-if="value.buttnType === 'export' || value.buttnType === 'import'"
    >
      <template slot="label" v-if="value.buttnType === 'import'">
        导入参数
        <el-tooltip
          effect="dark"
          content="导入参数中可以指定导入模型中字段固定值，如果该字段已经在模板中存在则会覆盖模板中的字段值"
          placement="top-start"
        >
          <i style="position: relative; z-index: 1" class="el-icon-question" />
        </el-tooltip>
      </template>
      <div class="ks-row-middle g6 poi codebg ks-col" @click="editJsx()">
        <div class="g9 f12 ks-col pl5 pr5">
          {{
            value.templateValues
              ? "export default function..."
              : "（空）点击添加自定义函数"
          }}
        </div>
      </div>
    </el-form-item>
    <el-form-item
      label="数据起始行号"
      v-if="value.buttnType === 'import' && value.templateType !== 'SYSTEM'"
    >
      <el-input-number
        :disabled="value.templateType === 'SYSTEM'"
        :min="value.headerRowNo + 1"
        size="small"
        style="width: 100%"
        v-model="value.startRowNo"
        controls-position="right"
      ></el-input-number>
    </el-form-item>
    <el-form-item
      label="标题行号"
      v-if="value.buttnType === 'import' && value.templateType !== 'SYSTEM'"
    >
      <el-input-number
        :disabled="value.templateType === 'SYSTEM'"
        size="small"
        style="width: 100%"
        v-model="value.headerRowNo"
        controls-position="right"
        :max="value.startRowNo - 1"
        :min="1"
      ></el-input-number>
    </el-form-item>
    <el-form-item
      label="自定义业务服务"
      class="tr"
      v-if="
        (value.buttnType === 'import' && value.templateType !== 'SYSTEM') ||
        value.buttnType === 'export'
      "
    >
      <el-switch v-model="value.customServe"></el-switch>
      <el-select
        v-if="value.customServe"
        v-model="value.processServeId"
        placeholder="默认"
        style="width: 100%"
      >
        <el-option
          :value="i.key"
          :label="i.name"
          v-for="(i, index) in btnServelist"
          :key="index"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item
      label="设置超时时间（秒）"
      class="tr"
      v-if="value.buttnType === 'export' || value.buttnType === 'import'"
    >
      <el-switch v-model="value.timeoutFlag"></el-switch>
      <el-input-number
        v-if="value.timeoutFlag"
        v-model="value.timeout"
        size="small"
        style="width: 100%"
        controls-position="right"
        :min="1"
      >
      </el-input-number>
    </el-form-item>
    <el-form-item label="数据校验不通过" v-if="value.buttnType === 'import'">
      <el-radio-group v-model="value.importOnError" style="width: 100%">
        <el-radio :label="false">全部不导入</el-radio>
        <el-radio :label="true">正确数据导入</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="重复数据" v-if="value.buttnType === 'import'">
      <el-radio-group v-model="value.importOnRepeat" style="width: 100%">
        <el-radio :label="false">不导入</el-radio>
        <el-radio :label="true">更新</el-radio>
      </el-radio-group>
    </el-form-item>
    <hmHook :value="value" v-if="value.buttnType === 'print'"></hmHook>
  </div>
</template>

<script>
import basicmixins from "./basicmixins";
import { getHmprinttemplateList } from "@/apis/paas/HmPrintTemplateController.js";
import { BUTTON_TYPES_ENUM, PAGE_TYPE_ENUM } from "@/utils/enum";
import { mapGetters } from "vuex";
import { getBasePath } from "@/config/api.config";
import { downloadFileSrc } from "@/utils/util.js";
import { getHmprocessList } from "@/apis/paas/HmProcessController.js";
import { getHmhttprequestdefinitionList } from "@/apis/paas/HmHttpRequestDefinitionController.js";
import { getHmpagefolderListTree } from "@/apis/paas/HmPageFolderController.js";
import { filterNodeMethod } from "@/utils/treeSelectFormat";
import { cloneDeep } from "lodash";
import { getHmexceltemplateList } from "@/apis/paas/HmExcelTemplateController.js";
const template = `/**
 * context    页面工具类对象,
 * rootScope  页面公共事件对象
 * @returns  Object
 */
function getQueryData(context,rootScope) {
  return {}
}`;
import monacoEditor from "./hlTableList/monacoEditor/index.js";
export default {
  async mounted() {
    this.initoptions(this.value.buttnType);
    if (this.value.processServeId) {
      this.changes(true);
    }
    if (!this.value.timeout) {
      this.$set(this.value, "timeout", 20);
    }
  },
  components: { hmHook: () => import("./hmHook/index") },
  computed: {
    ...mapGetters(["getModelTreeList", "getNavName", "getFormListInTree"]),
    BUTTON_TYPES_ENUM() {
      let arr = cloneDeep(BUTTON_TYPES_ENUM);
      // table 内的按钮特殊类型
      if (/^table_btn_/.test(this.value.key)) {
        arr.push(
          {
            key: "import",
            value: "导入",
          },
          {
            key: "export",
            value: "导出",
          }
        );
      }
      if (this.getNavName === "template") {
        arr.push({
          key: "modal_close",
          value: "关闭模态框",
        });
        arr.push({
          key: "submit_close",
          value: "提交且关闭模态框",
        });
      }
      return arr;
    },
  },
  data() {
    return {
      filterNodeMethod,
      PAGE_TYPE_ENUM,
      processlist: [], // 流程列表
      processServelist: [], // 流程服务
      btnServelist: [], // 自定义业务服务
      pageList: [], // 关联页面list
      printLists: [], //打印设计list
      templateArr: [], // 导入导出模板list
    };
  },
  watch: {
    "value.customServe": {
      handler: async function (v) {
        if (v) {
          //因不同版本问题部分正则是历史数据规则
          const tablekey = this.value.key.match(
            /(rowLayout_|loy_|tb_)\w+$/
          )?.[0];
          const modelCode = this.getFormModule(tablekey, this.getModelTreeList)
            .__config.modelCode;
          let btnServelist = await getHmhttprequestdefinitionList({
            modelCode,
          });
          this.btnServelist = btnServelist.filter((i) => {
            return (
              i.serviceType !== "BUILT_IN" ||
              i.key === "selectList" ||
              i.key === "selectByPage" ||
              i.key === "selectByIds"
            );
          });
        }
      },
      immediate: true,
    },
    "value.tempalteURL": {
      handler(val) {
        // 历史数据全为自定义模板
        if (val && !this.value.templateType) {
          this.$set(this.value, "templateType", "CUSTOM");
        }
      },
      immediate: true,
    },
    "value.buttnType": {
      async handler(val) {
        if (["import", "export"].includes(val)) {
          if (!this.value.templateType) {
            this.$set(this.value, "templateType", "SYSTEM");
          }
          if (this.value.systemplateKey) {
            this.value.systemplateKey = "";
            this.value.templateFile = "";
            this.value.templateFileName = "";
          }
          if (this.value.templateType === "SYSTEM") {
            this.value.headerRowNo = 2;
            await this.loadData();
          }
        }
      },
    },
    "value.templateType": {
      async handler(val) {
        if (val === "SYSTEM") {
          this.value.headerRowNo = 2;
          await this.loadData();
        }
      },
      immediate: true,
    },
    "value.systemplateKey": {
      handler(val) {
        if (val) {
          const file = this.templateArr?.filter((item) => {
            return item.key === val;
          })[0];
          this.$set(this.value, "templateFile", file?.templateFile || "");
          this.$set(this.value, "templateFileName", file?.name || "");
        }
      },
    },
  },
  methods: {
    download(fileUrl) {
      downloadFileSrc(
        getBasePath(fileUrl),
        fileUrl?.split("/")?.reverse()[0] || "模板"
      );
    },
    handleUploadSuccess(src) {
      this.value.tempalteURL = src;
    },
    // 向tree中获取对应key
    getFormModule(key, list) {
      let config = {};
      for (let i = 0; i < list.length; i++) {
        config = list[i];
        if (config.key === key) {
          return config;
        } else if (config?.children?.length > 0) {
          const c = this.getFormModule(key, config?.children);
          if (c) {
            return c;
          }
        }
      }
    },
    async changes(show) {
      if (show && this.value.formkey) {
        const modelCode = this.getFormModule(
          this.value.formkey,
          this.getModelTreeList
        ).__config.modelCode;
        let processServelist = await getHmhttprequestdefinitionList({
          modelCode,
        });
        this.processServelist = processServelist.filter((i) => {
          return i.serviceType !== "BUILT_IN" || i.key === "saveOrUpdate";
        });
      } else {
        this.processServelist = [];
      }
    },
    async getProcess() {
      this.processlist = await getHmprocessList({ activated: true });
    },
    // 获取页面列表
    async getPageList() {
      // this.pageList = await getHmpageListAll()
      const pageList = await getHmpagefolderListTree({ type: "ALL" });
      pageList.forEach((node) => {
        node.type = "folder";
      });
      this.pageList = this.createPageTreeNode(pageList);
    },
    async getHmprintList() {
      this.printLists = await getHmprinttemplateList();
    },
    chnageType(value) {
      this.value.processServeId = "";
      if (value === "auto") {
        this.value.formkey = "";
      }
      this.initoptions(value);
    },
    initoptions(type) {
      if (type === "process_start" || type === "process_handle") {
        this.getProcess();
      }
      if (type === "link_redirect") {
        this.getPageList();
      }
      if (type === "print") {
        this.getHmprintList();
      }
    },
    changePageItem(value) {
      this.pageList.forEach((item) => {
        if (item.key === value) {
          this.value.pageType = item.type;
        }
      });
    },
    createPageTreeNode(tree) {
      return cloneDeep(tree).map((node) => {
        node.disabled = node.type === "folder";
        if (node.pageResults) {
          node.id = "folder" + node.id;
          node.children = node.pageResults || [];
          node.children.forEach((item) => {
            item.name = `${item.name}（${PAGE_TYPE_ENUM[item.type]}）`;
            item.disabled = item.id === this.$route.query.id;
          });
        }
        return node;
      });
    },
    editJsx() {
      let jsx = this.value.templateValues || template;
      monacoEditor.showEdit(decodeURIComponent(jsx)).then((res) => {
        this.value.templateValues = encodeURIComponent(res);
      });
    },
    async loadData() {
      const tablekey = this.value.key.match(/(rowLayout_|loy_|tb_)\w+$/)?.[0];
      const modelCode = this.getFormModule(tablekey, this.getModelTreeList)
        .__config.modelCode;

      const data = await getHmexceltemplateList({
        modelCode: modelCode,
      });
      this.templateArr = data.filter(
        (item) => item.type === this.value.buttnType.toUpperCase()
      );
    },
  },
  mixins: [basicmixins],
};
</script>

<style lang="scss" scoped>
.filebox {
  height: 28px;
  border-radius: 2px;
  padding: 0 8px;
  background: #f4f9ff;
  margin-bottom: 8px;
}
.codebg {
  border: 1px solid #f1f1f1;
  width: 100%;
  &:hover {
    background-color: #f3f9ff;
  }
}
</style>
